package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import com.iwhalecloud.citybrain.flow.platform.manager.common.ErrorCode;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpDispatchWorkItemDto;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;

import java.util.Objects;

/**
 * @author: liyang
 * @date: 2021/12/25 14:21
 */
public class TurnTaskValidator {


    private TaskService taskService;

    /**
     * 是否校验用户信息
     */
    private boolean checkUser = true;

    @Data
    public static class ValidatorResult{

        public static ValidatorResult fail(int errorCode, String errorMsg) {
            return new ValidatorResult(errorCode,errorMsg);
        }

        public static ValidatorResult success() {
            return new ValidatorResult();
        }


        public ValidatorResult() {
            this.success = true;
        }

        public ValidatorResult(int errorCode, String errorMsg) {
            this.errorCode = errorCode;
            this.errorMsg = errorMsg;
        }

        /**
         * 验证是否通过
         */
        private boolean success;

        /**
         * 错误编码
         */
        private int errorCode;

        /**
         * 错误信息
         */
        private String errorMsg;

    }

    public TurnTaskValidator(TaskService taskService) {
        this.taskService = taskService;
    }

    public TurnTaskValidator(TaskService taskService,boolean checkUser) {
        this.taskService = taskService;
        this.checkUser = checkUser;
    }

    public ValidatorResult validate(HttpDispatchWorkItemDto httpDispatchWorkItemDto){
        if (StringUtils.isBlank(httpDispatchWorkItemDto.getWorkItemId())){
            return ValidatorResult.fail(ErrorCode.TASK_ID_IS_NULL.errCode(),ErrorCode.TASK_ID_IS_NULL.errMessage());
        }

        if (StringUtils.isBlank(httpDispatchWorkItemDto.getTurnToUserCode())){
            return ValidatorResult.fail(ErrorCode.TURN_TO_USER_CODE_NOT_EXIST.errCode(),ErrorCode.TURN_TO_USER_CODE_NOT_EXIST.errMessage());
        }

        if (checkUser && StringUtils.isBlank(httpDispatchWorkItemDto.getParticipantId())){
            return ValidatorResult.fail(ErrorCode.PARTICIPANTID_NOT_EXIST.errCode(),ErrorCode.PARTICIPANTID_NOT_EXIST.errMessage());
        }
        Task task = taskService.createTaskQuery().taskId(httpDispatchWorkItemDto.getWorkItemId()).singleResult();
        if (Objects.isNull(task)){
            return ValidatorResult.fail(ErrorCode.TASK_NOT_EXIST.errCode(),ErrorCode.TASK_NOT_EXIST.errMessage());
        }
        return ValidatorResult.success();
    }
}
